using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Text;
using System.Data;
using SqlSugar;
using System.Threading.Tasks;
using System.Linq.Expressions;
using MathNet.Numerics.Distributions;
using AttendanceSysytem.Models;


namespace AccessibilityTools.DB
{
    public class DataBaseClient
    {
        // 私有静态字段，用于存储Lazy<SqlSugarClient>实例
        private static readonly Lazy<SqlSugarClient> _sqlSugarClient = new Lazy<SqlSugarClient>(CreateSqlSugarClient);
        // 私有构造函数，防止外部实例化
        private DataBaseClient()
        { }
        // 公开一个静态属性来访问SqlSugarClient实例       
        public static SqlSugarClient Instance => _sqlSugarClient.Value;
        // 私有静态方法，用于创建SqlSugarClient实例
        private static SqlSugarClient CreateSqlSugarClient()
        
        {
            
            string dbType = ConfigurationManager.AppSettings["dbType"].ToString();
            string connectionStr = ConfigurationManager.ConnectionStrings["dbConnectionStr"].ConnectionString; // 确保ConfigurationManager可以正确处理键名

            var config = new ConnectionConfig()
            {
                ConnectionString = connectionStr,
                DbType = DbTypeSwitch(dbType),
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            };

            var client = new SqlSugarClient(config);
            client.CodeFirst.InitTables<WorkScheduling>(); //  
            client.CodeFirst.InitTables<Employees>(); //  
            client.CodeFirst.InitTables<SystemConfigs>();

            if(!client.Queryable<SystemConfigs>().Any())
            {
                //初始化一些配置
                client.Insertable(new SystemConfigs() { Configkey ="system.overtime.offset",Value = "10",Name="加班时间偏移值" }).ExecuteCommand();
            }
            
            return client;
        }
        // 私有静态方法，用于根据配置字符串转换DbType
        private static SqlSugar.DbType DbTypeSwitch(string type)
        {
            switch (type.ToLower())
            {
                case "sqlserver":
                    return SqlSugar.DbType.SqlServer;

                case "mysql":
                    return SqlSugar.DbType.MySql;

                case "sqlite":
                    return SqlSugar.DbType.Sqlite;

                default:
                    return SqlSugar.DbType.MySql;
            }
        }
    }


    public static class SqlSugarExtensions
    {
        public static ISugarQueryable<T> WithNoLockOrNot<T>(this ISugarQueryable<T> query, bool @lock = false)
        {
            if (@lock)
            {
                query = query.With(SqlWith.NoLock);
            }

            return query;
        }
    }


    public static class PredicateBuilder
    {
        public static Expression<Func<T, bool>> GetTrue<T>() { return f => true; }
        public static Expression<Func<T, bool>> GetFalse<T>() { return f => false; }

        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.AndAlso<T>(second, Expression.AndAlso);
        }

        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.AndAlso<T>(second, Expression.OrElse);
        }

        private static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2, Func<Expression, Expression, BinaryExpression> func)
        {
            var parameter = Expression.Parameter(typeof(T));

            var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
            var left = leftVisitor.Visit(expr1.Body);

            var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
            var right = rightVisitor.Visit(expr2.Body);

            return Expression.Lambda<Func<T, bool>>(
                func(left, right), parameter);
        }

        private class ReplaceExpressionVisitor : ExpressionVisitor
        {
            private readonly Expression _oldValue;
            private readonly Expression _newValue;

            public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
            {
                _oldValue = oldValue;
                _newValue = newValue;
            }

            public override Expression Visit(Expression node)
            {
                if (node == _oldValue)
                    return _newValue;
                return base.Visit(node);
            }
        }
    }


    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class DisplayNameAttribute : Attribute
    {
        public string DisplayName { get; }
        public bool Ignore { get; }

        public DisplayNameAttribute(string displayName, bool ignore = false)
        {
            DisplayName = displayName;
            Ignore = ignore;
        }
    }


    public interface IPageList<T> : IList<T>
    {
        int PageIndex { get; }
        int PageSize { get; }
        int TotalCount { get; }
        int TotalPages { get; }
        bool HasPreviousPage { get; }
        bool HasNextPage { get; }
    }

[Serializable]
    public class PageList<T> : List<T>, IPageList<T>
    {
        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="source">数据源</param>
        /// <param name="pageIndex">分页索引</param>
        /// <param name="pageSize">分页大小</param>
        public PageList(IQueryable<T> source, int pageIndex, int pageSize)
        {
            var total = source.Count();
            TotalCount = total;
            TotalPages = total / pageSize;

            if (total % pageSize > 0)
                TotalPages++;

            PageSize = pageSize;
            PageIndex = pageIndex;

            AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList());
        }

        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="source">数据源</param>
        /// <param name="pageIndex">分页索引</param>
        /// <param name="pageSize">分页大小</param>
        public PageList(IList<T> source, int pageIndex, int pageSize)
        {
            TotalCount = source.Count();
            TotalPages = TotalCount / pageSize;

            if (TotalCount % pageSize > 0)
                TotalPages++;

            PageSize = pageSize;
            PageIndex = pageIndex;
            AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList());
        }

        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="source">数据源</param>
        /// <param name="pageIndex">分页索引</param>
        /// <param name="pageSize">分页大小</param>
        /// <param name="totalCount">总记录数</param>
        public PageList(IEnumerable<T> source, int pageIndex, int pageSize, int totalCount)
        {
            TotalCount = totalCount;
            TotalPages = TotalCount / pageSize;

            if (TotalCount % pageSize > 0)
                TotalPages++;

            PageSize = pageSize;
            PageIndex = pageIndex;
            AddRange(source);
        }

        /// <summary>
        ///     分页索引
        /// </summary>
        public int PageIndex { get; }

        /// <summary>
        ///     分页大小
        /// </summary>
        public int PageSize { get; private set; }

        /// <summary>
        ///     总记录数
        /// </summary>
        public int TotalCount { get; }

        /// <summary>
        ///     总页数
        /// </summary>
        public int TotalPages { get; }

        /// <summary>
        ///     是否有上一页
        /// </summary>
        public bool HasPreviousPage => PageIndex > 0;

        /// <summary>
        ///     是否有下一页
        /// </summary>
        public bool HasNextPage => PageIndex + 1 < TotalPages;
    }


}


